package fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.a2032.R;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.SchedulersTransformer;
import com.example.a2032.Utils.SharedPreferenceUtils;
import com.example.a2032.Utils.Utils;
import com.example.a2032.fragment.BaseFragment;
import com.example.a2032.entity.RealTimeData;
import com.example.a2032.entity.RealTimeStepData;
import com.example.a2032.viewmodel.RealTimeStepViewModel;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DateFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DateFragment extends BaseFragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_time_hour)
    TextView tvTime;
    @BindView(R.id.tv_timeMode)
    TextView tvTimeMode;
    @BindView(R.id.iv_weather)
    ImageView ivWeather;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.iv_temp)
    ImageView ivTemp;
    @BindView(R.id.tv_tempValue)
    TextView tvStepValue;

    @BindArray(R.array.week_array)
    String[] weekArray;
    @BindView(R.id.tv_weekDays)
    TextView tvWeekDays;
    @BindView(R.id.iv_time_split)
    ImageView ivTimeSplit;
    @BindView(R.id.tv_time_minute)
    TextView tvTimeMinute;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private RealTimeStepViewModel realTimeStepViewModel;
    private int lastDay;

    public DateFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DateFragment newInstance() {
        DateFragment fragment = new DateFragment();
        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_date, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        compositeDisposable=new CompositeDisposable();
        Log.i(TAG, "init: "+compositeDisposable.hashCode()+" "+this.hashCode());
        subscribe(this);
        showDate();
        startDateTimer();

    }
    CompositeDisposable compositeDisposable;
    void getRealTimeData() {

       Utils.startTempMeasureTimer(compositeDisposable);

    }
    private static final String TAG = "DateFragment";
    Disposable timerDisposable;
    private void startDateTimer() {
        Observable.interval(1, TimeUnit.SECONDS).compose(SchedulersTransformer.io2MainObservable()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                timerDisposable=d;
            }

            @Override
            public void onNext(Long value) {
                showDate();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        getRealTimeData();
    }

    @Override
    public void onPause() {
        super.onPause();
        compositeDisposable.clear();
    }

    private void showDate(){
        boolean is24= SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_TimeMode,false);
        setTimeMode(is24);
        Calendar calendar = Calendar.getInstance();
        String formatString=is24?"HH:mm":"hh:mm a";
        SimpleDateFormat format = new SimpleDateFormat(formatString, Locale.getDefault());
        String formatTime=format.format(calendar.getTime());
        String[]timeArrays=null;
        if(is24){
            timeArrays=formatTime.split(":");
        }else {
            String[]modeArrays=formatTime.split(" ");
            timeArrays=modeArrays[0].split(":");
            String timePm=modeArrays[1];
            tvTimeMode.setText(timePm);
        }
        String hourString=timeArrays[0];
        String minString=timeArrays[1];
        int weekDays = calendar.get(Calendar.DAY_OF_WEEK);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String weekString = weekArray[weekDays - 1];

        tvTime.setText(hourString);
        tvTimeMinute.setText(minString);
        tvWeekDays.setText(weekString);
        tvDate.setText(Utils.getFormatDateString(month + 1, day, "."));
        lastDay = day;
    }

    private void setTimeMode(boolean is24){
        tvTimeMode.setVisibility(is24?View.INVISIBLE:View.VISIBLE);
    }
    @Override
    public void onDetach() {
        super.onDetach();
        unSubscribe(timerDisposable);
        compositeDisposable.dispose();
    //    compositeDisposable.dispose();
    }

    @Override
    public void TempData(float tempData) {
        super.TempData(tempData);
        showTempData(tempData);
    }

    private void showTempData(float tempData) {
        ivTemp.setImageResource(tempData>37.2?R.mipmap.temp_error:R.mipmap.temp_normal);
        tvStepValue.setText(Utils.getShowTemp(tempData)+Utils.getShowTempUnit());
    }
}